﻿using System;
using System.Collections.Generic;
using log4net;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;

namespace Matrix.MaKaYunShang.WeChat.AutoMsg
{
    /// <summary>
    /// 微信消息机器人
    /// </summary>
    public class MsgRobotProccess
    {
        private MxApiWechatInfo _wechatInfo;
        private MatrixCloudProjectInfo _p;
        private MxApiWeChatMsgRev _weChatMsgRev;
        private string _hostDomain;

        private readonly ILog _fileLog = LogManager.GetLogger(typeof(MsgRobotProccess));

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="wechatInfo"></param>
        public MsgRobotProccess(MxApiWechatInfo wechatInfo)
        {
            _wechatInfo = wechatInfo;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="wechatInfo"></param>
        /// <param name="weChatMsgRev"></param>
        public MsgRobotProccess(MxApiWechatInfo wechatInfo, MxApiWeChatMsgRev weChatMsgRev)
        {
            _wechatInfo = wechatInfo;
            _weChatMsgRev = weChatMsgRev;
        }

        #region 响应用户上行信息
        /// <summary>
        /// 消息机器人入口
        /// </summary>
        /// <returns></returns>
        public string MsgRobotWork()
        {

#if DEBUG
            _fileLog.Info("MsgRobotProccess | MsgRobotWork | received message content - " + _weChatMsgRev.MsgId);
#endif

            if (_wechatInfo == null || _wechatInfo.Id == 0 || string.IsNullOrWhiteSpace(_wechatInfo.AppId) ||
                string.IsNullOrWhiteSpace(_weChatMsgRev.FromUserName))
            {
                _fileLog.Error("MsgRobotProccess | MsgRobotWork | Invalid wechatInfo data or invalid weChatMsgRev data");
                return null;
            }
            string strReplyMsg;

            var strMsgType = _weChatMsgRev.MsgType;

            switch (strMsgType.ToLower())
            {
                case "text":
                case "image":
                case "voice":
                case "video":
                case "shortvideo":
                    strReplyMsg = ResponseToTextMsg();
                    break;
                case "event_subscribe":
                case "event_scan":
                    strReplyMsg = ResponseToSubcribeEvent();
                    break;
                case "link":
                default:
                    strReplyMsg = RobotMsg(_weChatMsgRev.FromUserName);
                    break;
            }

            return strReplyMsg;
        }

        /// <summary>
        /// 响应用户的文本信息
        /// </summary>
        /// <returns></returns>
        private string ResponseToTextMsg()
        {
            if (string.IsNullOrWhiteSpace(_weChatMsgRev.Content))
            {
                return RobotMsg(_weChatMsgRev.FromUserName);
            }

            var msgConfig = WeChatMsgConfigBLL.Instance.GetMsgConfigBySubmitContent(_wechatInfo.Id,
                _weChatMsgRev.Content, _weChatMsgRev.MsgType);
            if (msgConfig == null || msgConfig.Id == 0)
            {
                return RobotMsg(_weChatMsgRev.FromUserName);
            }

            return ReplyToMsg(msgConfig);
        }

        private string ResponseToSubcribeEvent()
        {
            var msgConfig = WeChatMsgConfigBLL.Instance.GetMsgConfigBySubmitContent(_wechatInfo.Id,
                _weChatMsgRev.Content, _weChatMsgRev.MsgType);
            if (msgConfig == null || msgConfig.Id == 0)
            {
                return RobotMsg(_weChatMsgRev.FromUserName);
            }

            if (msgConfig.MsgType == "news")
            {
                var lsArticles = WechatMsgArticleBLL.Instance.GetModelListByMsgConfigId(msgConfig.Id);
                if (lsArticles == null || lsArticles.Count == 0)
                {
                    msgConfig.MsgType = "text";
                }
                else
                {
                    msgConfig.WechatMsgArticleList = lsArticles;
                }
            }

            return ReplyToMsg(msgConfig);
        }


        #endregion

        #region 回复信息方法
        /// <summary>
        /// 回复信息处理入口
        /// </summary>
        /// <param name="weChatMsgConfig"></param>
        /// <returns></returns>
        private string ReplyToMsg(WeChatMsgConfig weChatMsgConfig)
        {
            string strReplyMsg;

            var strMsgType = weChatMsgConfig.MsgType;

            switch (strMsgType.ToLower())
            {
                case "text":
                case "image":
                case "voice":
                case "video":
                    strReplyMsg = ReplyCommonMsg(weChatMsgConfig);
                    break;
                case "news":
                    strReplyMsg = ReplyNewsMsg(weChatMsgConfig);
                    break;
                default:
                    strReplyMsg = RobotMsg(_weChatMsgRev.FromUserName);
                    break;
            }

            return strReplyMsg;
        }

        /// <summary>
        /// 通用信息回复
        /// </summary>
        /// <param name="weChatMsgConfig"></param>
        /// <returns></returns>
        private string ReplyCommonMsg(WeChatMsgConfig weChatMsgConfig)
        {
            if (string.IsNullOrWhiteSpace(weChatMsgConfig.ReplyMsgContent))
                return RobotMsg(_weChatMsgRev.FromUserName);

            var strReplyMsg = _wxInterMsgFunc.SendWxCommonMsg(_wechatInfo, _weChatMsgRev.FromUserName, weChatMsgConfig);
            return string.IsNullOrWhiteSpace(strReplyMsg) ? RobotMsg(_weChatMsgRev.FromUserName) : strReplyMsg;
        }

        /// <summary>
        /// 图文信息回复
        /// </summary>
        /// <param name="weChatMsgConfig"></param>
        /// <returns></returns>
        private string ReplyNewsMsg(WeChatMsgConfig weChatMsgConfig)
        {
            var lsArticles = new List<Article>();
            foreach (var configArticle in weChatMsgConfig.WechatMsgArticleList)
            {
                var article = new Article
                {
                    Title = configArticle.Title,
                    Description = configArticle.Description,
                    PicUrl = configArticle.PicUrl,
                    Url =
                        configArticle.Url.Replace("[WECHATINFOID]", "wechatInfoId=" + _wechatInfo.Id)
                            .Replace("[WXOPENID]", "openid=" + _weChatMsgRev.FromUserName)
                };

                lsArticles.Add(article);
            }

            return _wxInterMsgFunc.SendWxTxtPic(_wechatInfo, _weChatMsgRev.FromUserName, lsArticles);
        }

        /// <summary>
        /// 机器人回答
        /// 简易版 可升级为更高级的的机器人
        /// </summary>
        /// <returns></returns>
        public string RobotMsg(string toUserName)
        {
            string[] arrRobotMsgsList =
            {
                "感谢关注和使用",
                "码卡云商感谢你的光临！",
                "谢谢关注和使用。"
            };

            var nRobotMsgsLength = arrRobotMsgsList.Length;
            //var arRandomIndex = CommonHelper.GetRandomNum(1, 0, nRobotMsgsLenght-1);
            var ra = new Random(unchecked((int)DateTime.Now.Ticks));
            var arRandomIndex = ra.Next(0, nRobotMsgsLength - 1);

#if DEBUG
            _fileLog.Info("MsgRobotProccess | RobotMsg | Robot message: " + arrRobotMsgsList[arRandomIndex]);
#endif

            var weChatMsgConfig = new WeChatMsgConfig
            {
                Id = 9999,//临时写入，满足调用方法检验流程
                MsgType = "text",
                ReplyMsgContent = arrRobotMsgsList[arRandomIndex]
            };
            return _wxInterMsgFunc.SendWxCommonMsg(_wechatInfo, toUserName, weChatMsgConfig);
        }
        #endregion

    }
}